package dcedit.util;

// Import Java SDK Classes
import javax.swing.JTextField;
import java.awt.event.*;

/** IntegerField class */
public class IntegerField extends JTextField {
   /** Serializable constant */
   public static final long serialVersionUID = 1281482615747L;
	
   /** Field which specifies if the component will allow negatives as well as positives. */
   private boolean allowNegativeIntegers;

   /** constructor */
   public IntegerField() {
      this(0, true);
   } // END constructor

   /** constructor */
   public IntegerField(int num) {
      this(num, true);
   } // END constructor

   /** constructor */
   public IntegerField(boolean allowNegativeIntegers) {
      this(0, allowNegativeIntegers);
   } // END constructor

   /** constructor */
   public IntegerField(int num, boolean allowNegativeIntegers) {
      super(String.valueOf(num));
      this.allowNegativeIntegers = allowNegativeIntegers;
      this.addKeyListener(new KeyAdapter() {
         public void keyReleased(KeyEvent ke) {
            // TODO: This logic does not preserve caret position correctly.  Need to update.
            final IntegerField FIELD = (IntegerField)ke.getComponent();
            String text = FIELD.getText();
            int caretPosition = FIELD.getCaretPosition();
            // remove nondigits
            text = (FIELD.allowNegativeIntegers() && text.startsWith("-") ? "-" : "") + text.replaceAll("\\D", "");
            if(FIELD.allowNegativeIntegers() && text.startsWith("-")) caretPosition -= 2;
            FIELD.setText(text);
            FIELD.setCaretPosition(caretPosition);
         } // END keyReleased
      });
   } // END constructor

   /** allowNegativeIntegers method */
   public boolean allowNegativeIntegers() {
      return this.allowNegativeIntegers;
   } // END allowNegativeIntegers
} // END class IntegerField